class PluginTestKitGenerator < Rails::Generator::NamedBase
  
  attr_reader :plugin_name, :test_kit
  
  def initialize(runtime_args, runtime_options = {})
    
    super

    @plugin_name = @file_path

    @ptk_root = File.join(spec.path, '..', '..', '..')

    @plugin_root = File.join(@ptk_root, '..', @plugin_name)
    @destination_root = File.join(@plugin_root, 'test')

    usage unless File.directory?(@plugin_root)
    
    @ptk_lib_root = File.join(@ptk_root, 'lib', 'ptk', '') # so we can easily sub() the trailing /
    @kit_dirs, @kit_files = find_lib_files
    @ptk_relative_root = File.join('..', '..', '..', 'ptk') # in relation to spec.path/templates

#    %w(@plugin_name @ptk_root @source_root @destination_root @test_kit).each { |iv| STDERR.puts "#{iv} = #{instance_variable_get(iv).inspect}" }

  end
  
  def banner
    "Usage: #{$0} #{spec.name} name_of_your_plugin [options]"
  end
  
  def manifest
    record do |m|

      m.directory 'config'
      m.directory 'fixtures'
      m.directory 'lib'
      m.directory File.join('lib', 'ptk')

      @kit_dirs.each do |dir|
        m.directory File.join('lib', 'ptk', dir)
      end
      
      m.file 'database.yml', File.join('config', 'database.yml')
      m.file 'schema.rb', File.join('config', 'schema.rb')
      m.file 'routes.rb', File.join('config', 'routes.rb')
      m.file 'environment.rb', File.join('config', 'environment.rb')
      m.file 'ptk_helper.rb', 'ptk_helper.rb'
      
      @kit_files.each do |file|
        m.file File.join(@ptk_relative_root, file), File.join('lib', 'ptk', file)
      end
      
      m.readme 'after_generation'
    end
  end
  
  protected
  
  def find_lib_files
    files, directories = [], []
    raw = Dir.glob(File.join(@ptk_lib_root, '**', '*')).each do |i|
      file = i.sub(@ptk_lib_root, '')
      File.directory?(i) ? directories << file : files << file
    end
    [directories, files]
  end

end